<template>
  <div class="patient-select">
    <div class="header-action-row">
      <span class="section-bar"></span>
      <span class="page-title">诊断患者选择：</span>
    </div>
    <div class="header-divider"></div>
    <div class="action-bar">
      <button class="btn action" @click="openDiseaseDialog('other')">插入入院诊断</button>
      <button class="btn action" @click="openDiseaseDialog('primary')">插入主诊断</button>
      <button class="btn action" @click="openDiseaseDialog('other')">插入其他诊断</button>

    </div>
    <div class="action-bar">
      <button class="btn order" @click="addDrugOrder">增加药品处方医嘱</button>
      <button class="btn order" @click="addTreatmentOrder">增加诊疗项目医嘱</button>
      <button class="btn order" @click="addMedicalServiceOrder">增加医疗服务医嘱</button>
    </div>
    <div class="header-divider"></div>
    <div class="search-bar">
      <input v-model="searchName" class="form-input" placeholder="患者姓名" @keyup.enter="search" />
      <button class="btn primary" @click="search">搜索</button>
    </div>
    <div class="table-card">
      <table class="patient-table">
        <thead>
          <tr>
            <th class="index-col">序号</th>
            <th>住院号</th>
            <th>姓名</th>
            <th>身份证号</th>
            <th>性别</th>
            <th>工作状态</th>
            <th>科别类别</th>
            <th>入院时间</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, idx) in patients" :key="item.patientId" :class="{ 'selected-row': detail && detail.patientId === item.patientId }" @click="selectDetail(item)">
            <td class="index-col">{{ (page - 1) * pageSize + idx + 1 }}</td>
            <td>{{ item.idCard }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.identityNumber }}</td>
            <td>{{ item.gender }}</td>
            <td>{{ item.personCategory || '在职' }}</td>
            <td>{{ item.paymentType || '医保' }}</td>
            <td>{{ item.admissionTime }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="pagination-bar">
      <button class="btn page-btn" :disabled="page===1" @click="prevPage">上一页</button>
      <span class="current-page">第{{ page }}页/共{{ totalPage }}页</span>
      <button class="btn page-btn" :disabled="page===totalPage" @click="nextPage">下一页</button>
    </div>
    <div v-if="detail" class="detail-title-row">
      <span class="section-bar"></span>
      <span class="detail-title">患者详细信息</span>
    </div>
    <div v-if="detail" class="detail-form">
      <div class="detail-row">
        <div class="detail-item">
          <div class="label">住院号：</div>
          <input v-model="detail.idCard" class="form-input" />
        </div>
        <div class="detail-item">
          <div class="label">姓名：</div>
          <input v-model="detail.name" class="form-input" />
        </div>
        <div class="detail-item">
          <div class="label">身份证号：</div>
          <input v-model="detail.identityNumber" class="form-input" />
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <div class="label">年龄：</div>
          <input v-model="detail.age" class="form-input" type="number" min="0" max="120" />
        </div>
        <div class="detail-item">
          <div class="label">出生日期：</div>
          <input v-model="detail.birthDate" class="form-input" type="date" />
        </div>
        <div class="detail-item">
          <div class="label">性别：</div>
          <select v-model="detail.gender" class="form-input">
            <option value="男">男</option>
            <option value="女">女</option>
          </select>
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <div class="label">支付类型：</div>
          <select v-model="detail.paymentType" class="form-input">
            <option value="医保">医保</option>
            <option value="自费">自费</option>
          </select>
        </div>
        <div class="detail-item">
          <div class="label">人员类型：</div>
          <select v-model="detail.personCategory" class="form-input">
            <option value="在职">在职</option>
            <option value="退休">退休</option>
          </select>
        </div>
        <div class="detail-item">
          <div class="label">医院等级：</div>
          <select v-model="detail.hospitalLevel" class="form-input">
            <option value="三">三</option>
            <option value="二">二</option>
            <option value="一">一</option>
          </select>
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-item">
          <button class="btn primary" @click="updatePatientInfo" :disabled="loading">
            {{ loading ? '更新中...' : '更新患者信息' }}
          </button>
        </div>
      </div>
      
      <div style="margin-top:24px;">
        <div class="diagnosis-section">
          <h4>入院诊断 ({{ admissionDiagnoses.length }}条)</h4>
          <ul class="diagnosis-list">
            <li v-for="d in admissionDiagnoses" :key="d.id" class="diagnosis-item">
              <span class="diagnosis-name">{{ d.diseaseName || d.diagnosisDescription }}</span>
              <span class="diagnosis-type">{{ d.isPrimary === 1 ? '主要' : '次要' }}</span>
              <button class="btn-delete" @click="removeDiagnosis(d)">删除</button>
            </li>
            <li v-if="admissionDiagnoses.length === 0" class="no-data">暂无入院诊断</li>
          </ul>
        </div>
        
        <div class="diagnosis-section">
          <h4>主要诊断 ({{ primaryDiagnoses.length }}条)</h4>
          <ul class="diagnosis-list">
            <li v-for="d in primaryDiagnoses" :key="d.id" class="diagnosis-item">
              <span class="diagnosis-name">{{ d.diseaseName || d.diagnosisDescription }}</span>
              <button class="btn-delete" @click="removeDiagnosis(d)">删除</button>
            </li>
            <li v-if="primaryDiagnoses.length === 0" class="no-data">暂无主要诊断</li>
          </ul>
        </div>
        
        <div class="diagnosis-section">
          <h4>其他诊断 ({{ otherDiagnoses.length }}条)</h4>
          <ul class="diagnosis-list">
            <li v-for="d in otherDiagnoses" :key="d.id" class="diagnosis-item">
              <span class="diagnosis-name">{{ d.diseaseName || d.diagnosisDescription }}</span>
              <button class="btn-delete" @click="removeDiagnosis(d)">删除</button>
            </li>
            <li v-if="otherDiagnoses.length === 0" class="no-data">暂无其他诊断</li>
          </ul>
        </div>
      </div>
    </div>
    
    <!-- 疾病选择对话框 -->
    <div v-if="showDiseaseDialog" class="dialog-overlay" @click="showDiseaseDialog = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>选择疾病 - {{ selectedDiseaseType === 'primary' ? '主要诊断' : '次要诊断' }}</h3>
          <button class="btn-close" @click="showDiseaseDialog = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="search-row">
            <input 
              v-model="diseaseSearchKeyword" 
              class="form-input" 
              placeholder="输入疾病名称搜索，留空显示常见疾病..." 
              @input="handleDiseaseSearch"
              @keyup.enter="searchDiseases"
            />
            <button class="btn primary" @click="searchDiseases">
              搜索
            </button>
          </div>
          <div class="disease-list">
            <div v-if="availableDiseases.length === 0 && !diseaseSearchKeyword.trim()" class="no-data">
              正在加载常见疾病列表...
            </div>
            <div v-else-if="availableDiseases.length === 0 && diseaseSearchKeyword.trim()" class="no-data">
              未找到包含"{{ diseaseSearchKeyword.trim() }}"的疾病
            </div>
            <div v-else-if="availableDiseases.length > 0" class="search-result-info">
              <span v-if="diseaseSearchKeyword.trim()">找到 {{ availableDiseases.length }} 个相关疾病，点击选择：</span>
              <span v-else>常见疾病列表（{{ availableDiseases.length }} 个），点击选择：</span>
            </div>
            <div 
              v-for="disease in availableDiseases" 
              :key="disease.id" 
              class="disease-item"
              @click="addDiagnosis(disease)"
            >
              <div class="disease-name">{{ disease.diseaseName || disease.name }}</div>
              <div class="disease-code">编码: {{ disease.diseaseCode || disease.code || '无' }}</div>
              <div v-if="disease.diseaseDescription" class="disease-desc">{{ disease.diseaseDescription }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 医嘱选择对话框 -->
    <OrderDialog
      :visible="showDrugOrderDialog"
      type="药品"
      title="选择药品 - 药品处方医嘱"
      search-placeholder="输入药品名称搜索，留空显示常用药品..."
      :items="availableDrugs"
      :on-search="searchDrugs"
      :on-load-default="loadDefaultDrugs"
      @close="showDrugOrderDialog = false"
      @add="handleAddDrugOrder"
    />

    <OrderDialog
      :visible="showTreatmentOrderDialog"
      type="诊疗项目"
      title="选择诊疗项目 - 诊疗项目医嘱"
      search-placeholder="输入诊疗项目名称搜索，留空显示常用项目..."
      :items="availableTreatments"
      :on-search="searchTreatments"
      :on-load-default="loadDefaultTreatments"
      @close="showTreatmentOrderDialog = false"
      @add="handleAddTreatmentOrder"
    />

    <OrderDialog
      :visible="showServiceOrderDialog"
      type="医疗服务"
      title="选择医疗服务 - 医疗服务医嘱"
      search-placeholder="输入医疗服务名称搜索，留空显示常用服务..."
      :items="availableServices"
      :on-search="searchServices"
      :on-load-default="loadDefaultServices"
      @close="showServiceOrderDialog = false"
      @add="handleAddServiceOrder"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import eventBus from '@/utils/eventBus'
import OrderDialog from '@/components/hospital/OrderDialog.vue'
import { 
  pageQueryInsuredPerson, 
  updateInsuredPerson,
  getPatientDiseases,
  addPatientDisease,
  deletePatientDisease,
  searchDiseasesByName,
  pageQueryDiseases,
  // 医嘱相关API
  addPatientDrugOrder,
  addPatientServiceOrder,
  addPatientServiceItemOrder,
  searchDrugsByName,
  pageQueryDrugs,
  searchMedicalServicesByName,
  pageQueryMedicalServices,
  searchMedicalServiceItemsByName,
  pageQueryMedicalServiceItems
} from '@/api/admission'

const searchName = ref('')
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const patients = ref([])
const detail = ref(null)
const loading = ref(false)
const diseases = ref([]) // 患者的疾病列表
const showDiseaseDialog = ref(false)
const diseaseSearchKeyword = ref('')
const availableDiseases = ref([])
const selectedDiseaseType = ref('primary') // primary: 主要诊断, other: 次要诊断
const searchTimer = ref(null) // 搜索防抖定时器

// 医嘱对话框相关状态
const showDrugOrderDialog = ref(false)
const showTreatmentOrderDialog = ref(false)
const showServiceOrderDialog = ref(false)
const availableDrugs = ref([])
const availableTreatments = ref([])
const availableServices = ref([])

// 计算属性：入院诊断（主要+次要）
const admissionDiagnoses = computed(() => {
  if (!diseases.value) return []
  return diseases.value
})

// 计算属性：主要诊断
const primaryDiagnoses = computed(() => {
  if (!diseases.value) return []
  return diseases.value.filter(d => d.isPrimary === 1)
})

// 计算属性：次要诊断
const otherDiagnoses = computed(() => {
  if (!diseases.value) return []
  return diseases.value.filter(d => d.isPrimary === 0)
})

// 搜索患者
async function search() {
  page.value = 1 // 搜索时重置到第一页
  await loadPatients()
}

// 加载患者列表
async function loadPatients() {
  loading.value = true
  console.log('开始加载患者列表，当前页:', page.value, '搜索条件:', searchName.value)
  
  try {
    const queryData = {
      pageNum: page.value,
      pageSize: pageSize.value,
      name: searchName.value.trim() || undefined
    }
    
    console.log('患者查询参数:', queryData)
    const response = await pageQueryInsuredPerson(queryData)
    console.log('患者查询响应:', response)
    
    if (response.flag && response.data) {
      patients.value = response.data.records || []
      total.value = response.data.total || 0
      
      // 转换数据格式以匹配模板
      patients.value = patients.value.map(patient => ({
        ...patient,
        idCard: patient.hospitalNumber || patient.idCard, // 住院号
        identityNumber: patient.idCard, // 身份证号
        admissionTime: patient.createTime ? new Date(patient.createTime).toLocaleString() : ''
      }))
      
      console.log('加载患者成功，数量:', patients.value.length, '总数:', total.value)
    } else {
      console.error('患者查询失败:', response.message)
      ElMessage.error(response.message || '查询患者列表失败')
      patients.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('查询患者列表失败:', error)
    ElMessage.error('查询患者列表失败，请稍后重试')
    patients.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页函数
async function prevPage() {
  if (page.value > 1) {
    page.value--
    await loadPatients()
  }
}

async function nextPage() {
  if (page.value < totalPage.value) {
    page.value++
    await loadPatients()
  }
}

// 选择患者详情
async function selectDetail(item) {
  detail.value = { ...item }
  await loadPatientDiseases(item.patientId)
  
  // 发送患者选择事件给其他页面
  eventBus.emit('patientSelected', detail.value)
}

// 加载患者疾病列表
async function loadPatientDiseases(patientId) {
  if (!patientId) return
  
  try {
    const response = await getPatientDiseases(patientId)
    if (response.flag && response.data) {
      diseases.value = response.data
    } else {
      diseases.value = []
    }
  } catch (error) {
    console.error('查询患者疾病失败:', error)
    diseases.value = []
  }
}

// 更新患者信息
async function updatePatientInfo() {
  if (!detail.value || !detail.value.patientId) {
    ElMessage.error('请先选择患者')
    return
  }
  
  try {
    const updateData = {
      patientId: detail.value.patientId,
      name: detail.value.name,
      idCard: detail.value.identityNumber,
      hospitalNumber: detail.value.idCard,
      age: detail.value.age,
      birthDate: detail.value.birth ? new Date(detail.value.birth).toISOString() : null,
      gender: detail.value.gender,
      address: detail.value.address,
      paymentType: detail.value.paymentType || '医保',
      personCategory: detail.value.personCategory || '在职',
      hospitalLevel: detail.value.hospitalLevel || '三'
    }
    
    const response = await updateInsuredPerson(updateData)
    
    if (response.flag) {
      ElMessage.success('患者信息更新成功')
      // 刷新列表
      await loadPatients()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新患者信息失败:', error)
    ElMessage.error('更新失败，请稍后重试')
  }
}

// 打开疾病选择对话框
async function openDiseaseDialog(type) {
  if (!detail.value) {
    ElMessage.error('请先选择患者')
    return
  }
  
  selectedDiseaseType.value = type
  showDiseaseDialog.value = true
  diseaseSearchKeyword.value = ''
  
  // 打开对话框时默认加载一些疾病数据
  await loadDefaultDiseases()
}

// 加载默认疾病列表
async function loadDefaultDiseases() {
  try {
    // 首先尝试使用分页查询获取疾病列表
    const response = await pageQueryDiseases({
      pageNum: 1,
      pageSize: 20 // 获取前20条作为默认显示
    })
    
    if (response.flag && response.data && response.data.records && response.data.records.length > 0) {
      availableDiseases.value = response.data.records
      console.log('默认疾病加载成功:', availableDiseases.value)
      return
    }
    
    // 如果分页查询没有数据，尝试使用一些常见的疾病关键词来获取默认数据
    const commonKeywords = ['感冒', '发烧', '咳嗽', '头痛', '胃痛', '高血压', '糖尿病', '肺炎', '腹泻', '失眠']
    
    for (const keyword of commonKeywords) {
      try {
        const searchResponse = await pageQueryDiseases({
          pageNum: 1,
          pageSize: 15,
          diseaseName: keyword
        })
        if (searchResponse.flag && searchResponse.data && searchResponse.data.records && searchResponse.data.records.length > 0) {
          availableDiseases.value = searchResponse.data.records
          console.log('通过关键词加载默认疾病成功:', keyword, availableDiseases.value)
          return
        }
      } catch (error) {
        console.log('关键词搜索失败:', keyword, error)
        continue
      }
    }
    
    // 如果所有方法都失败了
    availableDiseases.value = []
    console.log('无法加载默认疾病数据')
    
  } catch (error) {
    console.error('加载默认疾病失败:', error)
    availableDiseases.value = []
  }
}

// 搜索疾病 - 防抖处理
function handleDiseaseSearch() {
  if (diseaseSearchTimer.value) {
    clearTimeout(diseaseSearchTimer.value)
  }
  
  // 如果输入为空，显示默认疾病列表
  if (!diseaseSearchKeyword.value.trim()) {
    loadDefaultDiseases()
    return
  }
  
  diseaseSearchTimer.value = setTimeout(() => {
    searchDiseases()
  }, 500) // 500ms 防抖
}

// 搜索疾病
async function searchDiseases() {
  try {
    console.log('搜索疾病关键词:', diseaseSearchKeyword.value.trim())
    
    // 使用分页查询接口实现模糊搜索
    const response = await pageQueryDiseases({
      pageNum: 1,
      pageSize: 50, // 搜索时增加页面大小获取更多结果
      diseaseName: diseaseSearchKeyword.value.trim() || undefined // 使用diseaseName字段进行模糊查询
    })
    
    console.log('疾病搜索结果:', response) // 添加调试日志
    if (response.flag && response.data && response.data.records) {
      availableDiseases.value = response.data.records
      console.log('可用疾病列表:', availableDiseases.value) // 添加调试日志
    } else {
      availableDiseases.value = []
      console.log('搜索失败或无数据:', response.message)
    }
  } catch (error) {
    console.error('搜索疾病失败:', error)
    availableDiseases.value = []
    ElMessage.error('搜索疾病失败，请稍后重试')
  }
}

// 添加疾病诊断
async function addDiagnosis(disease) {
  if (!detail.value || !disease) return
  
  try {
    const diagnosisData = {
      patientId: detail.value.patientId,
      diseaseId: disease.id,
      isPrimary: selectedDiseaseType.value === 'primary' ? 1 : 0,
      diagnosisTime: new Date().toISOString(),
      diagnosisDescription: `${selectedDiseaseType.value === 'primary' ? '主要诊断' : '次要诊断'}: ${disease.diseaseName}`
    }
    
    const response = await addPatientDisease(diagnosisData)
    
    if (response.flag) {
      ElMessage.success('添加诊断成功')
      showDiseaseDialog.value = false
      // 刷新患者疾病列表
      await loadPatientDiseases(detail.value.patientId)
    } else {
      ElMessage.error(response.message || '添加诊断失败')
    }
  } catch (error) {
    console.error('添加诊断失败:', error)
    ElMessage.error('添加诊断失败，请稍后重试')
  }
}

// 删除疾病诊断
async function removeDiagnosis(diagnosis) {
  try {
    await ElMessageBox.confirm('确定要删除这个诊断吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deletePatientDisease(diagnosis.id)
    
    if (response.flag) {
      ElMessage.success('删除诊断成功')
      // 刷新患者疾病列表
      await loadPatientDiseases(detail.value.patientId)
    } else {
      ElMessage.error(response.message || '删除诊断失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除诊断失败:', error)
    ElMessage.error('删除诊断失败，请稍后重试')
  }
}

// 添加药品处方医嘱
async function addDrugOrder() {
  if (!detail.value) {
    ElMessage.error('请先选择患者')
    return
  }
  
  showDrugOrderDialog.value = true
  await loadDefaultDrugs()
}

// 添加诊疗项目医嘱
async function addTreatmentOrder() {
  if (!detail.value) {
    ElMessage.error('请先选择患者')
    return
  }
  
  showTreatmentOrderDialog.value = true
  await loadDefaultTreatments()
}

// 添加医疗服务医嘱
async function addMedicalServiceOrder() {
  if (!detail.value) {
    ElMessage.error('请先选择患者')
    return
  }
  
  showServiceOrderDialog.value = true
  await loadDefaultServices()
}

// 计算总页数
const totalPage = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 页面加载时自动获取患者列表
onMounted(async () => {
  console.log('PatientSelect页面加载完成，开始自动加载患者列表...')
  try {
    await loadPatients()
    console.log('患者列表自动加载完成')
  } catch (error) {
    console.error('页面初始化时加载患者列表失败:', error)
    ElMessage.error('页面初始化失败，请刷新页面重试')
  }
})

// 页面卸载时清理定时器
onUnmounted(() => {
  if (searchTimer.value) {
    clearTimeout(searchTimer.value)
  }
})

// 药品医嘱相关函数
async function loadDefaultDrugs() {
  try {
    console.log('加载默认药品列表')
    const response = await pageQueryDrugs({
      pageNum: 1,
      pageSize: 20
    })
    
    if (response.flag && response.data && response.data.records && response.data.records.length > 0) {
      availableDrugs.value = response.data.records
      console.log('默认药品加载成功，数量:', availableDrugs.value.length)
      return
    }
    
    // 如果没有数据，尝试使用常见药品关键词进行模糊搜索
    const commonDrugs = ['阿司匹林', '布洛芬', '对乙酰氨基酚', '阿莫西林', '头孢', '青霉素', '感冒药', '止痛药']
    
    for (const drug of commonDrugs) {
      try {
        console.log('尝试搜索常见药品:', drug)
        const searchResponse = await pageQueryDrugs({
          pageNum: 1,
          pageSize: 15,
          drugName: drug
        })
        if (searchResponse.flag && searchResponse.data && searchResponse.data.records && searchResponse.data.records.length > 0) {
          availableDrugs.value = searchResponse.data.records
          console.log('通过关键词加载默认药品成功:', drug, '数量:', availableDrugs.value.length)
          return
        }
      } catch (error) {
        console.log('搜索常见药品失败:', drug, error)
        continue
      }
    }
    
    availableDrugs.value = []
    console.log('无法加载默认药品数据')
  } catch (error) {
    console.error('加载默认药品失败:', error)
    availableDrugs.value = []
  }
}

async function searchDrugs(keyword) {
  try {
    console.log('搜索药品关键词:', keyword)
    
    // 使用分页查询接口实现模糊搜索
    const response = await pageQueryDrugs({
      pageNum: 1,
      pageSize: 50, // 搜索时增加页面大小获取更多结果
      drugName: keyword ? keyword.trim() : undefined // 使用drugName字段进行模糊查询
    })
    
    console.log('药品搜索响应:', response)
    
    if (response.flag && response.data && response.data.records) {
      availableDrugs.value = response.data.records
      console.log('药品搜索成功，数量:', availableDrugs.value.length)
    } else {
      availableDrugs.value = []
      console.log('药品搜索无结果:', response.message)
    }
  } catch (error) {
    console.error('搜索药品失败:', error)
    availableDrugs.value = []
    ElMessage.error('搜索药品失败，请稍后重试')
  }
}

async function handleAddDrugOrder(orderData) {
  const { item: drug, params } = orderData
  
  try {
    const requestData = {
      patientId: detail.value.patientId,
      drugId: drug.drugId || drug.id, // 修复drugId问题
      drugName: drug.drugName || drug.name,
      specification: drug.specification || '',
      dosage: params.dosage,
      frequency: params.frequency,
      days: params.days,
      quantity: params.quantity,
      unit: drug.unit || '片',
      orderTime: new Date().toISOString(),
      status: 'pending',
      remark: params.remark || ''
    }
    
    console.log('药品医嘱请求数据:', requestData) // 调试日志
    
    const response = await addPatientDrugOrder(requestData)
    
    if (response.flag) {
      ElMessage.success('添加药品处方医嘱成功')
      showDrugOrderDialog.value = false
      eventBus.emit('refreshPatientOrders', detail.value.patientId)
    } else {
      ElMessage.error(response.message || '添加药品处方医嘱失败')
    }
  } catch (error) {
    console.error('添加药品处方医嘱失败:', error)
    ElMessage.error('添加药品处方医嘱失败，请稍后重试')
  }
}

// 诊疗项目医嘱相关函数
async function loadDefaultTreatments() {
  try {
    console.log('加载默认诊疗项目列表')
    const response = await pageQueryMedicalServices({
      pageNum: 1,
      pageSize: 20
    })
    
    if (response.flag && response.data && response.data.records && response.data.records.length > 0) {
      availableTreatments.value = response.data.records
      console.log('默认诊疗项目加载成功，数量:', availableTreatments.value.length)
      return
    }
    
    // 如果没有数据，尝试使用常见诊疗项目关键词进行模糊搜索
    const commonTreatments = ['血常规', 'B超', 'CT', 'X光', '心电图', '尿常规', '血压测量', '体温测量']
    
    for (const treatment of commonTreatments) {
      try {
        console.log('尝试搜索常见诊疗项目:', treatment)
        const searchResponse = await pageQueryMedicalServices({
          pageNum: 1,
          pageSize: 15,
          projectName: treatment
        })
        if (searchResponse.flag && searchResponse.data && searchResponse.data.records && searchResponse.data.records.length > 0) {
          availableTreatments.value = searchResponse.data.records
          console.log('通过关键词加载默认诊疗项目成功:', treatment, '数量:', availableTreatments.value.length)
          return
        }
      } catch (error) {
        console.log('搜索常见诊疗项目失败:', treatment, error)
        continue
      }
    }
    
    availableTreatments.value = []
    console.log('无法加载默认诊疗项目数据')
  } catch (error) {
    console.error('加载默认诊疗项目失败:', error)
    availableTreatments.value = []
  }
}

async function searchTreatments(keyword) {
  try {
    console.log('搜索诊疗项目关键词:', keyword)
    
    // 使用分页查询接口实现模糊搜索
    const response = await pageQueryMedicalServices({
      pageNum: 1,
      pageSize: 50, // 搜索时增加页面大小获取更多结果
      projectName: keyword ? keyword.trim() : undefined // 使用projectName字段进行模糊查询
    })
    
    console.log('诊疗项目搜索响应:', response)
    
    if (response.flag && response.data && response.data.records) {
      availableTreatments.value = response.data.records
      console.log('诊疗项目搜索成功，数量:', availableTreatments.value.length)
    } else {
      availableTreatments.value = []
      console.log('诊疗项目搜索无结果:', response.message)
    }
  } catch (error) {
    console.error('搜索诊疗项目失败:', error)
    availableTreatments.value = []
    ElMessage.error('搜索诊疗项目失败，请稍后重试')
  }
}

async function handleAddTreatmentOrder(orderData) {
  const { item: treatment, params } = orderData
  
  try {
    const requestData = {
      patientId: detail.value.patientId,
      serviceId: treatment.serviceId || treatment.id,
      serviceName: treatment.projectName || treatment.serviceName || treatment.name,
      specification: treatment.specification || '',
      quantity: params.quantity,
      unit: treatment.unitOfMeasure || treatment.unit || '次',
      unitPrice: params.unitPrice || treatment.price || 0,
      orderTime: new Date().toISOString(),
      status: 'pending',
      remark: params.remark || ''
    }
    
    console.log('诊疗项目医嘱请求数据:', requestData) // 调试日志
    
    const response = await addPatientServiceOrder(requestData)
    
    if (response.flag) {
      ElMessage.success('添加诊疗项目医嘱成功')
      showTreatmentOrderDialog.value = false
      eventBus.emit('refreshPatientOrders', detail.value.patientId)
    } else {
      ElMessage.error(response.message || '添加诊疗项目医嘱失败')
    }
  } catch (error) {
    console.error('添加诊疗项目医嘱失败:', error)
    ElMessage.error('添加诊疗项目医嘱失败，请稍后重试')
  }
}

// 医疗服务医嘱相关函数
async function loadDefaultServices() {
  try {
    console.log('加载默认医疗服务列表')
    const response = await pageQueryMedicalServiceItems({
      pageNum: 1,
      pageSize: 20
    })
    
    if (response.flag && response.data && response.data.records && response.data.records.length > 0) {
      availableServices.value = response.data.records
      console.log('默认医疗服务加载成功，数量:', availableServices.value.length)
      return
    }
    
    // 如果没有数据，尝试使用常见医疗服务关键词进行模糊搜索
    const commonServices = ['床位费', '护理费', '监护费', '手术费', '麻醉费', '输血费', '注射费', '输液费']
    
    for (const service of commonServices) {
      try {
        console.log('尝试搜索常见医疗服务:', service)
        const searchResponse = await pageQueryMedicalServiceItems({
          pageNum: 1,
          pageSize: 15,
          projectName: service
        })
        if (searchResponse.flag && searchResponse.data && searchResponse.data.records && searchResponse.data.records.length > 0) {
          availableServices.value = searchResponse.data.records
          console.log('通过关键词加载默认医疗服务成功:', service, '数量:', availableServices.value.length)
          return
        }
      } catch (error) {
        console.log('搜索常见医疗服务失败:', service, error)
        continue
      }
    }
    
    availableServices.value = []
    console.log('无法加载默认医疗服务数据')
  } catch (error) {
    console.error('加载默认医疗服务失败:', error)
    availableServices.value = []
  }
}

async function searchServices(keyword) {
  try {
    console.log('搜索医疗服务关键词:', keyword)
    
    // 使用分页查询接口实现模糊搜索
    const response = await pageQueryMedicalServiceItems({
      pageNum: 1,
      pageSize: 50, // 搜索时增加页面大小获取更多结果
      projectName: keyword ? keyword.trim() : undefined // 使用projectName字段进行模糊查询
    })
    
    console.log('医疗服务搜索响应:', response)
    
    if (response.flag && response.data && response.data.records) {
      availableServices.value = response.data.records
      console.log('医疗服务搜索成功，数量:', availableServices.value.length)
    } else {
      availableServices.value = []
      console.log('医疗服务搜索无结果:', response.message)
    }
  } catch (error) {
    console.error('搜索医疗服务失败:', error)
    availableServices.value = []
    ElMessage.error('搜索医疗服务失败，请稍后重试')
  }
}

async function handleAddServiceOrder(orderData) {
  const { item: service, params } = orderData
  
  try {
    const requestData = {
      patientId: detail.value.patientId,
      itemId: service.itemId || service.id, // 修正：使用itemId而不是serviceItemId
      quantity: params.quantity,
      orderTime: new Date().toISOString(),
      doctorId: 1 // 临时使用固定值，实际应该从用户信息获取
    }
    
    console.log('医疗服务医嘱请求数据:', requestData) // 调试日志
    
    const response = await addPatientServiceItemOrder(requestData)
    
    if (response.flag) {
      ElMessage.success('添加医疗服务医嘱成功')
      showServiceOrderDialog.value = false
      eventBus.emit('refreshPatientOrders', detail.value.patientId)
    } else {
      ElMessage.error(response.message || '添加医疗服务医嘱失败')
    }
  } catch (error) {
    console.error('添加医疗服务医嘱失败:', error)
    ElMessage.error('添加医疗服务医嘱失败，请稍后重试')
  }
}
</script>

<style scoped>
.patient-select {
  background: #fff;
  border-radius: 8px;
  margin: 32px 0 0 0;
  padding: 24px 0 24px 0;
  max-width: 1400px;
  margin-left: auto;
  margin-right: auto;
  box-shadow: none;
}
.header-action-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 18px;
  margin-bottom: 12px;
  padding: 0 32px;
}
.section-bar {
  width: 4px;
  height: 22px;
  background: #409eff;
  border-radius: 2px;
  margin-right: 10px;
  display: inline-block;
}
.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #222;
  margin-right: 12px;
}
.header-divider {
  height: 1px;
  background: #e5e6eb;
  margin: 0 32px 18px 32px;
  border-radius: 1px;
}
.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
  padding: 0 32px;
}
.btn {
  padding: 0 18px;
  border-radius: 6px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  background: #f5f6fa;
  color: #34495e;
  cursor: pointer;
  transition: background 0.18s, box-shadow 0.18s, transform 0.18s;
  box-shadow: none;
  height: 32px;
  line-height: 32px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.btn.action {
  background: #eaf4ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}
.btn.order {
  background: #f0f9ff;
  color: #0ea5e9;
  border: 1px solid #7dd3fc;
}
.btn.primary {
  background: #409eff;
  color: #fff;
  border: none;
}
.btn.page-btn {
  background: #409eff;
  color: #fff;
  border: none;
  min-width: 60px;
}
.btn:hover, .btn:focus {
  background: #e0e6f6;
  color: #3076c9;
}
.btn.action:hover {
  background: #d1e9ff;
  color: #3076c9;
}
.btn.order:hover {
  background: #e0f2fe;
  color: #0369a1;
}
.btn.primary:hover, .btn.page-btn:hover {
  background: #3076c9;
  color: #fff;
}
.btn:active {
  transform: scale(0.97);
}
.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  padding: 0 32px;
}
.form-input {
  height: 32px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  padding: 0 10px;
  font-size: 14px;
  box-sizing: border-box;
  min-width: 160px;
  background: #fff;
  color: #222;
  box-shadow: 0 1px 2px rgba(64,158,255,0.04);
  transition: border 0.18s, box-shadow 0.18s;
}
.form-input:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.form-input::placeholder {
  color: #bfcbd9;
  opacity: 1;
}
.table-card {
  background: none;
  border-radius: 0;
  box-shadow: none;
  margin: 40px 32px 40px 32px;
  padding: 0;
}
.patient-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  border-radius: 0;
  overflow: hidden;
  font-size: 13px;
}
.patient-table th, .patient-table td {
  border: 1px solid #f0f0f0;
  padding: 8px 6px;
  text-align: center;
  font-size: 13px;
  font-weight: 400;
}
.patient-table th {
  background: #f7f8fa;
  color: #222;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
}
.patient-table .index-col {
  background: #f5f8fd;
  color: #888;
  width: 48px;
}
.patient-table tbody tr {
  transition: background 0.18s, box-shadow 0.18s;
  cursor: pointer;
}
.patient-table tbody tr:hover {
  background: #eaf4ff;
  box-shadow: -3px 0 0 0 #409eff inset;
}
.patient-table tbody tr.selected-row {
  background: #d0e8ff;
  box-shadow: -3px 0 0 0 #409eff inset;
}
.pagination-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0 0 32px;
}
.page-select {
  height: 28px;
  border-radius: 4px;
  border: 1.5px solid #409eff;
  font-size: 13px;
  padding: 0 8px;
  color: #222;
  background: #fff;
  outline: none;
  transition: border 0.18s;
}
.page-select:focus {
  border: 1.5px solid #3076c9;
}
.current-page {
  font-weight: 600;
  color: #409eff;
  border: 1.5px solid #409eff;
  border-radius: 4px;
  padding: 0 8px;
  background: #f7f8fa;
}
.detail-title-row {
  display: flex;
  align-items: center;
  margin: 18px 0 8px 32px;
}
.detail-title-row .section-bar {
  height: 18px;
  margin-right: 8px;
}
.detail-title {
  font-size: 15px;
  font-weight: 700;
  color: #222;
  text-align: left;
}
.detail-form {
  background: #fafbfc;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  padding: 24px 32px 12px 32px;
  margin: 0;
  border-top: 1px solid #e5e6eb;
}
.detail-row {
  display: flex;
  flex-wrap: wrap;
  gap: 0 36px;
  margin-bottom: 10px;
}
.detail-item {
  min-width: 220px;
  max-width: 320px;
  font-size: 15px;
  color: #34495e;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.detail-item .label {
  color: #222;
  font-size: 15px;
  font-weight: 500;
  width: 80px;
  text-align: right;
  margin-right: 8px;
  flex-shrink: 0;
}
.detail-item .form-input,
.detail-item select,
.detail-item input[type='date'] {
  height: 40px;
  border-radius: 8px;
  border: 1.5px solid #bfcbd9;
  background: #fff;
  font-size: 15px;
  color: #222;
  padding: 0 14px;
  box-sizing: border-box;
  outline: none;
  transition: border 0.2s, box-shadow 0.2s;
  width: 100%;
}
.detail-item .form-input:focus,
.detail-item select:focus,
.detail-item input[type='date']:focus {
  border: 1.5px solid #409eff;
  box-shadow: 0 0 0 2px #eaf4ff;
}
.detail-item select {
  appearance: none;
  -webkit-appearance: none;
  background: #fff url('data:image/svg+xml;utf8,<svg fill="%23349eff" height="18" viewBox="0 0 24 24" width="18" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>') no-repeat right 12px center/18px 18px;
  padding-right: 36px;
}

/* 诊断管理样式 */
.diagnosis-section {
  margin-bottom: 16px;
}

.diagnosis-section h4 {
  font-size: 16px;
  color: #34495e;
  margin-bottom: 8px;
  font-weight: 600;
}

.diagnosis-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.diagnosis-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 6px;
  border: 1px solid #e9ecef;
}

.diagnosis-name {
  flex: 1;
  color: #34495e;
  font-size: 14px;
}

.diagnosis-type {
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 8px;
}

.btn-delete {
  background: #ffebee;
  color: #d32f2f;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.btn-delete:hover {
  background: #ffcdd2;
}

.no-data {
  color: #999;
  font-style: italic;
  padding: 16px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.dialog-header h3 {
  margin: 0;
  color: #34495e;
  font-size: 16px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.btn-close:hover {
  background: #e9ecef;
}

.dialog-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.search-row {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.search-row .form-input {
  flex: 1;
}

.disease-list {
  max-height: 400px;
  overflow-y: auto;
}

.disease-item {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.disease-item:hover {
  background: #e3f2fd;
  border-color: #2196f3;
}

.disease-name {
  font-size: 14px;
  color: #34495e;
  font-weight: 500;
  margin-bottom: 4px;
}

.disease-code {
  font-size: 12px;
  color: #999;
}

.disease-desc {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.disease-item:hover .disease-name {
  color: #2196f3;
}

.disease-item:hover .disease-code {
  color: #2196f3;
}

.search-result-info {
  padding: 8px 12px;
  background: #e8f5e8;
  color: #2e7d32;
  border-radius: 4px;
  margin-bottom: 8px;
  font-size: 13px;
  border: 1px solid #c8e6c9;
}

@media (max-width: 1200px) {
  .header-action-row, .search-bar, .table-card, .detail-form {
    padding-left: 8px;
    padding-right: 8px;
  }
  .detail-title-row {
    margin-left: 8px;
  }
  .detail-row {
    flex-direction: column;
    gap: 0;
  }
}
</style>